package cn.sx.controller;

/*
 *@program:sx_emall_ssm
 *@author: sx
 *@desc: 前台用户登录控制器
 *@Time: 2020/9/18  9:40
 */

import cn.sx.config.ExceptionInterceptor;
import cn.sx.entity.Orders;
import cn.sx.entity.User;
import cn.sx.service.*;
import cn.sx.util.PageUtil;
import cn.sx.util.SafeUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Objects;

@Controller
@RequestMapping("/index")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private TypesService typesService;
    @Resource
    private GoodsService goodsService;
    @Resource
    private CartService cartService;
    @Resource
    private OrdersService ordersService;




    /*前台用户注册界面*/
    @RequestMapping("/register")
    public String goRegister(){
        return "register.jsp";
    }
    @PostMapping("/register")
    public String register(User user , HttpServletRequest request){
        if (user.getUsername().isEmpty()) {
            request.setAttribute("msg","用户名不能为空！");
        }else if(Objects.nonNull(userService.getByUsername(user.getUsername()))){
            request.setAttribute("msg","用户已经存在！");
        }else{
            userService.add(user);
            request.setAttribute("msg","注册成功，可以登陆了");
            return "/index/login.jsp";
        }
        return "/index/register.jsp";
    }
    /*前台用户登录界面*/
    @GetMapping("/login")
    public String goLogin(){
        return "login.jsp";
    }
    /*登录 */
    @PostMapping("/login")
    public String Login(User user,HttpServletRequest request, HttpSession session){
        //获取用户名和密码
        User loginuser = userService.getByUsernameAndPassword(user.getUsername(),user.getPassword());
        //判断用户名和密码是否为空
        if (loginuser == null){
            request.setAttribute("msg","账号或密码错误");
            return "/index/login.jsp";
        }else {
            //还原购物车
            session.setAttribute("cartCount",cartService.getCount(loginuser.getId()));
            String referer = request.getHeader("referer");//页面来源
            System.out.println(referer);
            session.setAttribute("user",loginuser);
            return "redirect:index";
        }
    }
    /*退出登录  */
    @RequestMapping("/logout")
    public String doLogout(HttpSession sess){
        try {
            sess.removeAttribute("user");
        }catch (Exception e){
            e.printStackTrace();
        }
        try {
            sess.removeAttribute("msg");

        }catch (Exception e){
            e.printStackTrace();
        }try{//退出后清除购物车数据
            sess.removeAttribute("cartCount");
        }catch (Exception e){
            e.printStackTrace();
        }
        return "redirect:index";
    }




    /*跳转到我的订单界面*/
    @RequestMapping("/order")
    public String goMyOrder(HttpServletRequest request,HttpSession session,
                            @RequestParam(required = false,defaultValue = "1")int page,
                            @RequestParam(required = false,defaultValue = "6")int size)//一页显示多少数据)
     {
         User user = (User) session.getAttribute("user");
         request.setAttribute("orderList",ordersService.getListByUseid(user.getId(),page,size));
         request.setAttribute("pageHtml", PageUtil.getPageHtml(request,ordersService.getCountByUserid(user.getId()),page,size));
        return "/index/order.jsp";
    }
    /*跳转到收获地址*/
    @RequestMapping("/address")
    public String goMyAddress(){
        return "/index/address.jsp";
    }
    /*修改收获地址信息*/
    @PostMapping("/addressUpdate")
    public String updateAddress (String name ,String phone,String address,HttpServletRequest request,HttpSession session){
        User user = (User) session.getAttribute("user");
        userService.updateAddress(user.getId(),name,phone,address);
        session.setAttribute("user",userService.get(user.getId()));
        request.setAttribute("msg","修改成功");
        return "/index/address.jsp";
    }
    /*跳转到修改密码*/
    @RequestMapping("/password")
    public String goUpdatePassword(){
        return "/index/password.jsp";
    }
//    修改用户密码
    @PostMapping("/passwordUpdate")
    public String updatePassword(String password,String passwordNew,HttpSession session,HttpServletRequest request){
        User user = (User) session.getAttribute("user");
        user = userService.get(user.getId());
        if(!user.getPassword().equals(SafeUtil.encode(password))){
            request.setAttribute("msg","原始密码错误");
        }else {
            userService.updateUsersPassword(user.getId(),passwordNew);
            request.setAttribute("msg","密码修改成功");
        }
        return "/index/password.jsp";
    }



    //购物车相关
    /*加入购物车*/
    @PostMapping("/cartBuy")
    public @ResponseBody boolean cartBuy(int goodId,HttpSession session){
        User user= (User) session.getAttribute("user");
        return cartService.save(goodId,user.getId());
    }
    /*跳转购物车界面*/
    @RequestMapping("/cart")
    public String Cart(HttpServletRequest reques,HttpSession session){
        User user = (User) session.getAttribute("user");
        reques.setAttribute("cartList",cartService.getList(user.getId()));
        reques.setAttribute("cartCount",cartService.getCount(user.getId()));
        reques.setAttribute("cartTotal",cartService.getTotal(user.getId()));
        return "/index/cart.jsp";
    }
    /*购物车总金额*/
    @GetMapping("/cartTotal")
    public @ResponseBody int cartTotal(HttpSession session){
        User user = (User) session.getAttribute("user");
        return cartService.getTotal(user.getId());
    }
    /*购物车结算*/
    @GetMapping("/orderSave")
    public String orderSaver(ServletRequest request,HttpSession session)throws ExceptionInterceptor.MyException {
        User user = (User) session.getAttribute("user");
        request.setAttribute("cartList",cartService.getList(user.getId()));
        int orderId=ordersService.save(user.getId());
        session.removeAttribute("cartCount");//清理购物车
        return "redirect:orderPay?id="+orderId;
    }
    /*跳转支付界面*/
    @GetMapping("/orderPay")
    public  String orderPay(int id,HttpServletRequest request) {
        request.setAttribute("order",ordersService.get(id));
        return "/index/pay.jsp";
    }
    /*支付成功*/
    @PostMapping("/orderPay")
    public String orderPay(Orders orders){
        ordersService.pay(orders);
        return "/index/payok.jsp";
    }
    /*购物车里面商品加号添加*/
    @ResponseBody
    @PostMapping("/cartAdd")
    public boolean cartAdd(int id){
        return cartService.add(id);
    }
    /*购物车商品减少*/
    @ResponseBody
    @PostMapping("/cartLess")
    public boolean cartLess(int id){
        return cartService.less(id);
    }
    /*购物车里面的商品删除*/
    @PostMapping("/cartDelete")
    public @ResponseBody boolean cartDelete(int id){
        return cartService.cartDelete(id);
    }
}
